package com.visionork.android.tai.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;

import com.visionork.android.tai.model.adapter.TaiAdapterBase;
import com.visionork.android.tai.model.adapter.VideoAdapter;


public class Episode implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String title;
	private String urlLink;
	protected TaiAdapterBase dataAdapter;
	private final ArrayList<Video> videos;

	public Episode() {
		videos = new ArrayList<Video>();
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getTitle() {
		return title;
	}

	public void setUrlLink(String urlLink) {
		this.urlLink = urlLink;
	}

	public String getUrlLink() {
		return urlLink;
	}

	public ArrayList<Video> getVideos() {
		return getVideos(true);
	}

	public ArrayList<Video> getVideos(boolean useCache) {
		if (!useCache) {
			@SuppressWarnings("unchecked")
			Collection<? extends Video> data = (Collection<? extends Video>) getDataAdapter()
					.getData();
			mergeData(data);
		}
		return videos;
	}

	private void mergeData(Collection<? extends Video> data) {
		for (Video video : data) {
			if (!videos.contains(video)) {
				/* add new one */
				videos.add(video);
			} else {
				/* update old one */
				Video existVideo = videos.get(videos.indexOf(video));
				existVideo.setTitle(video.getTitle());
			}
		}

		/* remove expired one */
		for (Video video : videos) {
			if (!data.contains(video)) {
				videos.remove(video);

			}
		}
		
	}

	@Override
	public boolean equals(Object obj) {
		return getUrlLink().equals(((Episode) obj).getUrlLink());
	}

	public ArrayList<Video> getVideosRef() {
		return videos;
	}
	
	private TaiAdapterBase getDataAdapter() {
		if (dataAdapter == null) {
			dataAdapter = new VideoAdapter(urlLink);
		}
		return dataAdapter;
	}

	public Video getVideoByUrlLink(String urlString) {
		for (Video video : videos) {
			if (video.getUrlLink().equals(urlString)) {
				return video;
			}
		}
		return null;
	}
}
